/*
 * set_address.c - fill in a sockaddr_in structure
 *
 *  Created on: Jun 1, 2014
 *      Author: Lhmily
 */
#include "../include/base.h"
void set_address(char *hname, char *sname, struct sockaddr_in *sap,
		char *protocol) {
	struct servent *sp;
	struct hostent *hp;
	char *endptr;
	short port;

	bzero(sap, sizeof(*sap));
	sap->sin_family = AF_INET;
	if (NULL != hname) {
		if (!inet_aton(hname, &sap->sin_addr)) {
			hp = gethostbyname(hname);
			if (NULL == hp)
				error(1, 0, "unknown host: %s\n", hname);
			sap->sin_addr = *(struct in_addr *) hp->h_addr;
		}
	} else {
		sap->sin_addr.s_addr=htonl(INADDR_ANY);
	}

	//set port
	port = strtol(sname, &endptr, 0);
	if ('\0' == *endptr)
		sap->sin_port = htons(port);
	else {
		sp = getservbyname(sname, protocol);
		if (NULL == sp)
			error(1, 0, "unknown service: %s\n", sname);
		sap->sin_port = sp->s_port;
	}
}

